<?php
class aa{
    public function uepay($post)
    {
        /**
         *  'orderInfo'=>$params,
         * 'payInfo'=>$payway,
         * 'gatewayApiUrl'=>request()->domain(),
         * 'checkout_token'=>$checkout_token
         */

        $payway = $post['payInfo'];
        $params = $post['orderInfo'];
        $order_no =  $params['invoice'];
        $domain_token = $params['invoice'];
        $bsite_domain = $params['bsite_domain'];
        $bsite_domain_site = "https://" . $bsite_domain;
        $gatewayApiUrl = $post['gatewayApiUrl'];
        $gateway_url = $payway['api_payurl'];

        $agentId = $payway['merchant_id'];
        $merNo = $payway['merchant_name'];

        $products = $params['order']['products'];
        $order_products = array();
        $title = '';
        foreach ($products as $item) {
            $title = $item['title'];
        }

        if($payway['remark'] == 'test'){
            $apiUrl = $gateway_url.'/createOrder';
//            $public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6f86G1b7qPO2PLXba6TDYF81xKVn8yxn2XtBuvv14n+WCPp7QpnwF/Pv6+2VtOOsMQtmUs/5qj56D9rGcSnCCsxvBU17DDAadRS2gMeY+IGpclzXYOI4vTu5KD+35u/H9Vf1fQzwSM0BUdO3IgEfr/dD57dDnH3qhLs3add+ER4aFhA6SenjYgSZaPoizgLMja4tep2c5E4uJQEHl7gFBDGZ7A3TFASbVzvUlnS484Su+GFtjHZJsgspozVlo6CAPL/SPE4S91/sWhlurHXc+CpfvMC3OwJwrhMjhaZkLJzFnPOGGXmTH88moE8sK85tZivbPAimUvfQ8V1plOoNXQIDAQAB';
            $private_key = 'MIIEowIBAAKCAQEA2HcYXm2QOCppsFDT/o0289cYPlIRFNntBMD5DHa3dJFuVnXFqu9iJYdkVO3y7ZEFNp5LRL0K2SJMkg03Ee+n2PpaDXPefLcP2qSfI2K/s8UQPKHLHCJYz0FtaAZmDQqzqpw6tdiXpCvVXfiUU6eY/RJ7dVCjgudpZnZ/VYxtBQN+ToRQFGBvqmz9adOxQ6gHHcjoaFD2RpkMxhGXA7P7oNV5jFvnK7+cvnG2rS+W9O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IKKW0DFw7EekMPuJ4xewaW0HOd2jkhtJjaA4Wet25cXaE5dne7f9jtK4QM/QDaqX+GNJFmBOGGSf2kKbBH8dq4ApQKBgEI1uWfQ3CR7yhH2Hmj1RL0qQqp9qjiFi1KzczjJI8/vtdNJze0JGKlSDA18ejLEp9ClECDnuRt1/Y5tU68ozeUdDvB9FzFVZg4kirQCPmJtHgfXmSpdphge4VlV+Lqqh4mNk2B0YyXEG8c7ULhejpw5VBAI02B22u3SinTSmGbT';
        }else{
            $apiUrl = $gateway_url.'/createOrder';
//            $public_key = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6f86G1b7qPO2PLXba6TDYF81xKVn8yxn2XtBuvv14n+WCPp7QpnwF/Pv6+2VtOOsMQtmUs/5qj56D9rGcSnCCsxvBU17DDAadRS2gMeY+IGpclzXYOI4vTu5KD+35u/H9Vf1fQzwSM0BUdO3IgEfr/dD57dDnH3qhLs3add+ER4aFhA6SenjYgSZaPoizgLMja4tep2c5E4uJQEHl7gFBDGZ7A3TFASbVzvUlnS484Su+GFtjHZJsgspozVlo6CAPL/SPE4S91/sWhlurHXc+CpfvMC3OwJwrhMjhaZkLJzFnPOGGXmTH88moE8sK85tZivbPAimUvfQ8V1plOoNXQIDAQAB';
            $private_key = 'MIIEowIBAAKCAQEA2HcYXm2QOCppsFDT/o0289cYPlIRFNntBMD5DHa3dJFuVnXFqu9iJYdkVO3y7ZEFNp5LRL0K2SJMkg03Ee+n2PpaDXPefLcP2qSfI2K/s8UQPKHLHCJYz0FtaAZmDQqzqpw6tdiXpCvVXfiUU6eY/RJ7dVCjgudpZnZ/VYxtBQN+ToRQFGBvqmz9adOxQ6gHHcjoaFD2RpkMxhGXA7P7oNV5jFvnK7+cvnG2rS+W9OKTpYCOi9BXoeXxcOlIxQlIUSwcniwTg4qGLaRRZFp4MZBO87q4geRsu+4CfQ60ZgeHJ3WAEVh+Gta965xORbQNIqvJoVMbCEPLKaAawHVbywIDAQABAoI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RL0qQqp9qjiFi1KzczjJI8/vtdNJze0JGKlSDA18ejLEp9ClECDnuRt1/Y5tU68ozeUdDvB9FzFVZg4kirQCPmJtHgfXmSpdphge4VlV+Lqqh4mNk2B0YyXEG8c7ULhejpw5VBAI02B22u3SinTSmGbT';
        }

        $phone = $params['order']['shipping_info']['phone'];
        $country = $params['order']['shipping_info']['country'];
        $phoneNumberUtil = \libphonenumber\PhoneNumberUtil::getInstance();
        $phoneNumberObject = $phoneNumberUtil->parse($phone, $country);
        $phone = "+".$phoneNumberObject->getCountryCode().$phoneNumberObject->getNationalNumber();

        $products = $params['order']['products'];
        $order_products = array();
        $product_id = '';
        foreach ($products as $item) {
            $product_id = "Pro".rand(110,99999);
            $order_products[] = array(
                'goodsName'   => $item['title'],
                'price'    => $item['price'],
                'count'    => $item['quantity'],
            );
        }

        $postData = [
            'orderNo'=>$order_no,
            'transAmt'=>$params['order']['amount'],
            'firstName'=>$params['order']['bill_info']['first_name'],
            'lastName'=>$params['order']['bill_info']['last_name'],
            'email'=>$params['order']['bill_info']['email'],
            'phoneNo'=>$phone,
            'country'=>$params['order']['shipping_info']['country'],
            'state'=>$params['order']['shipping_info']['state'],
            'city'=>$params['order']['shipping_info']['city'],
            'zip'=>$params['order']['shipping_info']['zipcode'],
            'goodsName'=>"physical",
            'goodsList'=>json_encode($order_products),
            'currency'=>840,
            'website'=>$bsite_domain,
            'notifyUrl'=>$bsite_domain_site.'/gateway/notify.php?mxtoken='.$domain_token,
            'returnUrl'=>$bsite_domain_site.'/gateway/redirect.php?mxtoken='.$domain_token,
            'transType'=>'SALES',
            'custIp'=>$params['order']['ip'],
            'signType'=>'RSA',
            'version'=>'1.0',
            'agentId'=>$agentId,
            'merNo'=>$merNo,
        ];
        // 过滤空值字段
        $postData = array_filter($postData, function($value) {
            return $value !== '';
        });
        ksort($postData);
        $stringToBeSigned = '';
        foreach ($postData as $k => $v) {
            $stringToBeSigned .= $k . '=' . $v . '&';
        }
        $stringToBeSigned = trim($stringToBeSigned,'&');

        $key = "-----BEGIN PRIVATE KEY-----\n" .
            wordwrap($private_key, 64, "\n", true) .
            "\n-----END PRIVATE KEY-----";
        $privatekey = openssl_get_privatekey($key);
        openssl_sign($stringToBeSigned, $sign, $privatekey, OPENSSL_ALGO_SHA256);
        $mysign =  base64_encode($sign);

        $postData['signature'] = $mysign;

        $httpheader = [];
        $httpheader[] = "nomerge";
        $httpheader[] = "Content-Type: application/x-www-form-urlencoded";
        $transaction = $this->httpCurl($apiUrl,http_build_query($postData),$httpheader);

        trace_log(json_encode($transaction),'uepay');
        $res['code'] = 0;
        $res['pay_url'] = '';
        $res['msg'] = '';
        $res['html'] = '';
        $res['request_begin_log'] = [];
        $res['request_end_log'] = [];

        if(isset($transaction['code']) && $transaction['code'] == 1212){
            //失败
            $res['code'] = $transaction['code'];
            $res['msg'] = $transaction['msg'];
            return $res;
        }
        if(empty($transaction['data'])){
            $msg = $transaction['respMsg'] ?: '请求失败未知错误';
            $res['code'] = 1005;
            $res['msg'] = $msg;
            return $res;
        }

        $year = $params['order']['card']['exp_year'];
        $month = $params['order']['card']['exp_month'];
        if(strlen($year) == 4){
            $year = mb_substr($year,2);
        }
        $orderId = $transaction['data']['orderId'];
        $postData2 = [
            'orderId'=>$orderId,
            'productId'=>$product_id,
            'transType'=>'SALES',
            'signType'=>'RSA',
            'version'=>1.0,
            'agentId'=>$agentId,
            'merNo'=>$merNo,
//            'signature'=>'',
            'cardNo'=>$params['order']['card']['card_no'],
            'expDate'=>$year.$month,//2712
            'cvv'=>$params['order']['card']['cvv'],
            'currency'=>840,
            'browserLanguage'=>$params['browerlang'],
        ];

        // 过滤空值字段
        $postData2 = array_filter($postData2, function($value) {
            return $value !== '';
        });
        ksort($postData2);
        $stringToBeSigned = '';
        foreach ($postData2 as $k => $v) {
            $stringToBeSigned .= $k . '=' . $v . '&';
        }
        $stringToBeSigned = trim($stringToBeSigned,'&');
        openssl_sign($stringToBeSigned, $sign, $privatekey, OPENSSL_ALGO_SHA256);
        $mysign =  base64_encode($sign);

        $postData2['signature'] = $mysign;

        $apiUrl = $gateway_url."/pay";
        $httpheader = [];
        $httpheader[] = "nomerge";
        $httpheader[] = "Content-Type: application/x-www-form-urlencoded";
        $transaction = $this->httpCurl($apiUrl,http_build_query($postData2),$httpheader);
        if(isset($transaction['code']) && $transaction['code'] == 1212){
            //失败
            $res['code'] = $transaction['code'];
            $res['msg'] = $transaction['msg'];
            return $res;
        }
        if(empty($transaction['data'])){
            $msg = $transaction['respMsg'] ?: '请求失败未知错误';
            $res['code'] = 1005;
            $res['msg'] = $msg;
            return $res;
        }

        $res['code'] = 0;
        $res['msg'] = "success";
        $res['pay_url'] = $postData['returnUrl'];

        return $res;
    }
}
